import Vue from "vue";
import VueRouter from "vue-router";
import about from '../components/about'
import friendly from '../components/friendly'
import index from '../components/index'
import loading from '../components/loading'
import articledetails from '../components/articledetails'
import tags from '../components/tags'

import store from '../store/index.js'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 要告诉 vue 使用 vueRouter
Vue.use(VueRouter);

// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器，
// 或者，只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
  { path: '/', component: index, meta: { requiresAuth: true,title:'周黎的个人博客'} },
  { path: '/search', component: index, props: (route) => ({ query: route.query.key }), meta: { requiresAuth: true,title:'文章搜索' } },
  { path: '/home/about', component: about, meta: { requiresAuth: true ,title:'关于本站'} },
  { path: '/home/friendly', component: friendly, meta: { requiresAuth: true, title: '友情链接' } },
  { path: '/home/tags', component: tags, meta: { requiresAuth: true ,title:'本站标签'} },
  { path: '/home/article/:articleid.html', component: articledetails, meta: { requiresAuth: true, title: '文章详情' } },
  { path: '/loading', component: loading ,title:'全速加载中....'},
  {
    // 会匹配所有路径(404处理)
    path: '*', redirect:'/'
  }
]


// 3. 创建 router 实例，然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
  routes, // (缩写) 相当于 routes: routes
  mode: 'history',
  base: __dirname
})

// 页面刷新时，重新赋值token
if (sessionStorage.getItem('token')) {
  store.commit('set_token', sessionStorage.getItem('token'))
  }
router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.meta.requiresAuth) {
    //这里的requireAuth为路由中定义的 meta:{requireAuth:true}，意思为：该路由添加该字段，表示进入该路由需要登陆的
    if (store.state.token) {
      next();
    }
    else {
      next({
        path: '/loading',
        query: { redirect: to.fullPath }
      })
    }
  }
  else {
    next();
  }
})
export default router;